package com.mes.warehouse.server.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mes.common.pojo.MESResult;
import com.mes.common.util.Constant;
import com.mes.pojo.warehouse.Warehouse;
import com.mes.warehouse.mapper.WarehouseMapper;
import com.mes.warehouse.server.WarehouseServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 张喆
 * @Company
 * @Description
 * @Time 2024/10/24 14:57
 */
@Service
public class WarehouseServerImpl implements WarehouseServer {
    @Autowired
    private WarehouseMapper warehouseMapper;

    @Override
    public MESResult selectAll(Warehouse warehouse, Integer pageNum, Integer limit) {
        PageHelper.startPage(pageNum,limit);
        List<Warehouse> warehouseList = warehouseMapper.selectAll(warehouse);
        PageInfo<Warehouse> warehousePageInfo = new PageInfo<>(warehouseList);
        return MESResult.success(warehousePageInfo);
    }

    @Override
    public MESResult selectById(String warehouseId) {
        return MESResult.success(warehouseMapper.selectById(warehouseId));
    }

    @Override
    public MESResult deleteWarehouse(String warehouseId) {
        Warehouse warehouse = warehouseMapper.selectById(warehouseId);
        warehouse.setWarehouseStatus(99);
        return MESResult.success(warehouseMapper.updateWarehouse(warehouse));
    }

    @Override
    public MESResult updateWarehouse(Warehouse warehouse) {
        Warehouse same = warehouseMapper.selectByName(warehouse.getWarehouseName());
        if (same != null && !same.getWarehouseId().equals(warehouse.getWarehouseId())){
            return MESResult.error(Constant.RESPONSE_STATUS_REPEAT);
        }
        return MESResult.success(warehouseMapper.updateWarehouse(warehouse));
    }

    @Override
    public MESResult insertWarehouse(Warehouse warehouse) {
        Warehouse same = warehouseMapper.selectByName(warehouse.getWarehouseName());
        if (same != null){
            return MESResult.error(Constant.RESPONSE_STATUS_REPEAT);
        }
        String maxId = warehouseMapper.selectMaxId();
        String[] split = maxId.split("_");
        int num = Integer.parseInt(split[1]);
        num = num + 1;
        String strNum = null;
        if (num > 0 && num < 10){
            strNum = "000" + num;
        }else if (num < 100){
            strNum = "00" + num;
        }else if (num < 1000){
            strNum = "0" + num;
        }else {
            strNum = num + "";
        }
        warehouse.setWarehouseId(split[0] + "_" + strNum);
        return MESResult.success(warehouseMapper.insertWarehouse(warehouse));
    }
}
